package net.oschina.allchat.server.framework.pipe.stream.negotiants;

import net.oschina.allchat.message.processing.IProcessingFactory;
import net.oschina.allchat.protocol.core.stream.Stream;
import net.oschina.allchat.server.framework.core.integration.IMessage;
import net.oschina.allchat.server.framework.pipe.stream.IClientConnectionContext;
import net.oschina.allchat.server.framework.pipe.stream.IStreamNegotiant;

public abstract class AbstractNegotiant implements IStreamNegotiant {
	

	protected IStreamNegotiant next;
	protected boolean done = false;

	@Override
	public void setNext(IStreamNegotiant next) {
		this.next = next;
	}

	@Override
	public boolean negotiate(IClientConnectionContext context, IMessage message) {
		if (done) {
			if (next != null) {
				return next.negotiate(context, message);
			}
			
			return true;
		}
		
		if (doNegotiate(context, message)) {
			done = true;
		}
		
		return done && next == null;
	}
	
	protected void closeStream(IClientConnectionContext context, IProcessingFactory processingFactory) {
		context.write(processingFactory.translate(new Stream(true)));
		context.close();
	}

	protected abstract boolean doNegotiate(IClientConnectionContext context, IMessage message);

}
